package ua.kharkov.knure.pereverziev.diploma.web.command;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import ua.kharkov.knure.pereverziev.diploma.db.DAOServices.ServiceFactory;
import ua.kharkov.knure.pereverziev.diploma.db.entity.Airport;
import ua.kharkov.knure.pereverziev.diploma.db.entity.Route;
import ua.kharkov.knure.pereverziev.diploma.pathfinder.PathFinder;
import ua.kharkov.knure.pereverziev.diploma.web.util.DateTimeUtil;

public class AirportDateChoiceCommand implements Command {

	private static final Logger log = Logger
			.getLogger(AirportDateChoiceCommand.class);

	@Override
	public String execute(final HttpServletRequest request,
			final HttpServletResponse response) throws IOException,
			ServletException {
		log.info("StartPointChoiceCommand.Execute ");

		String forward = "/WEB-INF/jsp/error_page.jsp";

		final StringBuilder errorMessage = new StringBuilder();

		final HttpSession session = request.getSession();

		final String fromAirport = request.getParameter("fromAirport");
		log.debug("Request parameter: fromAirportID --> " + fromAirport);

		final String toAirport = request.getParameter("toAirport");
		log.debug("Request parameter: toAirportID --> " + toAirport);

		final String departuredate = request.getParameter("departuredate");
		log.debug("Request parameter: departuredate --> " + departuredate);

		final String returndate = request.getParameter("returndate");
		log.debug("Request parameter: returndate --> " + returndate);

		final String type = request.getParameter("type");
		log.debug("Request parameter: type --> " + type);

		// Parsing dates

		final Date dateDeparture = DateTimeUtil.parseDate(departuredate);

		if (dateDeparture == null) {
			log.error("Error while parsing date: " + departuredate);
			errorMessage.append("Wrong date \"" + departuredate + "\"!!\n");
		}

		if (type == null) {
			log.error("Select trip type ");
			errorMessage.append("Wrong type \"" + type + "\"!!\n");
		}

		if (errorMessage.length() != 0) {
			session.setAttribute("errorMessage", errorMessage);
			log.trace("Set the session attribute: errorMessage --> "
					+ errorMessage);
		} else {

			forward = "/WEB-INF/jsp/flightChoice.jsp?direction=1";

			log.debug("Parsed departure date="
					+ DateTimeUtil.getDateString(dateDeparture));

			final Airport departure = ServiceFactory.getInstance()
					.getAirportService().get(Long.parseLong(fromAirport));
			final Airport destination = ServiceFactory.getInstance()
					.getAirportService().get(Long.parseLong(toAirport));

			// error handler
			// set forward to error page

			if (fromAirport.equals(toAirport)) {
				errorMessage.append("Wrong destination!!<br/>");
			}

			final List<Route> directFlights = ServiceFactory.getInstance()
					.getFlightsService()
					.getFlights(dateDeparture, departure, destination);

			directFlights.addAll(PathFinder.FindPaths(departure, destination,
					dateDeparture));

			if (directFlights.size() == 0) {
				errorMessage.append("No direct flights found!!<br/>");
			}

			if (!"single".equals(type)) {
				final Date dateReturn = DateTimeUtil.parseDate(returndate);
				log.debug("Parsed return date="
						+ DateTimeUtil.getDateString(dateReturn));
				final List<Route> returnFlights = ServiceFactory.getInstance()
						.getFlightsService()
						.getFlights(dateReturn, destination, departure);
				returnFlights.addAll(PathFinder.FindPaths(destination,
						departure, dateReturn));

				if (returnFlights.size() == 0) {
					errorMessage.append("No return flights found!!<br/>");
				}
				session.setAttribute("returnFlights", returnFlights);
			}
			session.setAttribute("directFlights", directFlights);
			session.setAttribute("type", type);
		}

		if (errorMessage.length() != 0) {
			forward = (String) session.getAttribute("lastPage") + "?error="
					+ errorMessage.toString();
		} else {
			session.setAttribute("lastPage", forward);
		}
		log.debug("Command finished");
		return forward;
	}
}
